//
//  DingtouManagerTableViewController.m
//  HaoDeCaiFu
//
//  Created by 物联信息中心 on 2017/12/29.
//  Copyright © 2017年 郑开宏. All rights reserved.
//

#import "DingtouManagerTableViewController.h"
#import "DintouManagerTableViewCell.h"
#import "DingtouDetailViewController.h"
#import "FixThrowPlanListModel.h"
#import "HDCFOpenAccountVc.h"//开户页面
#import "UINavigationBar+Awesome.h"
@interface DingtouManagerTableViewController ()
{
    int page;
    int pageSize;
    FixThrowPlanListModel * planListModel;
    NSMutableArray * listArray;
}
@end

@implementation DingtouManagerTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
     [self.navigationController.navigationBar lt_reset];
   
    self.title=@"定投计划管理";
    //初始化
    page = 1;
    pageSize = 10;
    listArray = [NSMutableArray array];
    
    self.tableView.rowHeight=150;
    self.tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    [self.tableView registerNib:[UINib nibWithNibName:@"DintouManagerTableViewCell" bundle:nil] forCellReuseIdentifier:@"DintouManagerTableViewCell"];
    [self.tableView setTableFooterView:[[UIView alloc]initWithFrame:CGRectZero]];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(mainRefresh)];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(mainLoadMore)];
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
}
-(void)viewWillAppear:(BOOL)animated
{
    [self initDataOfList];
}
-(void)initDataOfList
{
    //先判断是否登录
    NSString *token = kToken;
    if (!(token.length > 0)) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请先登录！" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            HDCFLoginVc *loginVc = [[HDCFLoginVc alloc] init];
            [self.navigationController pushViewController:loginVc animated:NO];

        }];
        UIAlertAction * action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        }];

        [alert addAction: action1];
        [alert addAction: action2];
        [self presentViewController:alert animated:NO completion:nil];
        return;
    }
    
    //在判断是否开户
    NSString *openStatus = kOpenStatus;
    if (!(openStatus.integerValue > 0)){
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请先开户！" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            HDCFOpenAccountVc *loginVc = [[HDCFOpenAccountVc alloc] init];
            [self.navigationController pushViewController:loginVc animated:NO];

        }];
        UIAlertAction * action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        }];

        [alert addAction: action1];
        [alert addAction: action2];
        [self presentViewController:alert animated:NO completion:nil];
        return;
    }
    
    
    //获取定投列表
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"accountNumber"] = kAcount;
    dict[@"pageIndex"] = [NSString stringWithFormat:@"%d",page];
    dict[@"pageSize"] = [NSString stringWithFormat:@"%d",pageSize];
    dict[@"rspId"] = @"";//定投计划代码,如提供，则返回过滤后的数据
    dict[@"rspStatus"] = @"";//定投计划状态(如提供，则返回过滤后的数据)
    //LLLog(@"%@",dict);
    NSString *jsonString = [self dictionaryToJson:dict];
    NSDictionary *dictThree = @{
                                KparametTwo:@"/public/transaction/find-investor-rsp-plans"
                                };
    [HttpRequest sendPostRequestWithURL:nil WithParamets:dictThree WithJsonString:jsonString success:^(id result) {
        [SVProgressHUD dismiss];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        //NSLog(@"%@",result);
        
        if ([result[@"code"] isEqualToString:@"0000"]) {
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                [self.navigationController popViewControllerAnimated:YES];
//            });
            
            NSDictionary * dataDic = result[@"data"];
            NSArray * dataArray = dataDic[@"data"];
            
            if (page == 1) {
                [listArray removeAllObjects];
            }
            if ([dataArray count] == 0) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
                return;
            }
            
            for (int i = 0 ; i < dataArray.count ; i++) {
                planListModel = [FixThrowPlanListModel mj_objectWithKeyValues:dataArray[i]];
                //[FixThrowPlanListModel mj_replacedKeyFromPropertyName];
                
                [listArray addObject:planListModel];
            }
            [self.tableView reloadData];
        }else{
            [SVProgressHUD showInfoWithStatus:result[@"message"]];
            [SVProgressHUD dismissWithDelay:1.5];
        }
    } failure:^(NSError *errer) {
        LLLog(@"%@",errer);
        [SVProgressHUD showErrorWithStatus:@"服务器错误，获取失败"];
        [SVProgressHUD dismissWithDelay:1.0];
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return listArray.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DintouManagerTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"DintouManagerTableViewCell"];
    if (!cell) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"DintouManagerTableViewCell" forIndexPath:indexPath];
    }
    cell.selectionStyle =  UITableViewCellSelectionStyleNone;
    
    if (listArray.count > 0) {
        FixThrowPlanListModel * fixPlanModel = listArray[indexPath.row];
        cell.nameLable.text = [NSString stringWithFormat:@"%@",fixPlanModel.name];
        
        NSString * cycleStr;//
        NSString * dayStr;
        if ([fixPlanModel.cycle isEqualToString:@"weekly"]) {
            cycleStr = @"每星期";
            
            dayStr = [NSString stringWithFormat:@"星期%ld",(long)fixPlanModel.cycleDay];
        }
        else if ([fixPlanModel.cycle isEqualToString:@"biweekly"])
        {
            cycleStr = @"每两星期";
            dayStr = [NSString stringWithFormat:@"星期%ld",(long)fixPlanModel.cycleDay];
        }
        else if ([fixPlanModel.cycle isEqualToString:@"monthly"])
        {
            cycleStr = @"每月";
            dayStr = [NSString stringWithFormat:@"%ld日",fixPlanModel.cycleDay];
        }
        else if ([fixPlanModel.cycle isEqualToString:@"quarterly"])
        {
            cycleStr = @"每季";
            dayStr = [NSString stringWithFormat:@"%ld日",fixPlanModel.cycleDay];
        }
        cell.detailLable.text = [NSString stringWithFormat:@"%@ %@ 定投 %.2f元",cycleStr,dayStr,[fixPlanModel.rspAmount floatValue]];
        
        if ([fixPlanModel.rspStatus isEqualToString:@"active"]) {
            cell.rspStatusLabel.text = @"执行中";
            cell.rspStatusLabel.backgroundColor = RGB(2, 146, 22);
        }
        else if ([fixPlanModel.rspStatus isEqualToString:@"suspend"])
        {
            cell.rspStatusLabel.text = @"已暂停";
            cell.rspStatusLabel.backgroundColor = COLOR_NAV;
        }
        else if ([fixPlanModel.rspStatus isEqualToString:@"terminated"])
        {
            cell.rspStatusLabel.text = @"已终止";
            cell.rspStatusLabel.backgroundColor = RGB(204, 204, 204);
        }
        
        cell.nextTimeLable.text = [NSString stringWithFormat:@"下期扣款：%@",[self timeFromStr:fixPlanModel.nextRunDate]];
        cell.lastTimeLable.text = [NSString stringWithFormat:@"上期扣款：%@",[self timeFromStr:fixPlanModel.updatedDate]];
    }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    FixThrowPlanListModel * model = listArray[indexPath.row];
    DingtouDetailViewController*vc=[[DingtouDetailViewController alloc]init];
    vc.fixThrowPlanListModel = model;
    vc.fixThrowManagerVC = self;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)mainRefresh {
    page = 1;
    [self initDataOfList];
}

- (void)mainLoadMore {
    page ++;
    [self initDataOfList];
}
#pragma mark -
#pragma mark 字典转json字符串
- (NSString *)dictionaryToJson:(NSDictionary *)dic{
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSString *jsonTemp = [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    return jsonTemp;
}
#pragma mark -
#pragma mark 时间戳转化成标准时间
-(NSString *)timeFromStr:(NSString *)time
{
    //时间戳转化成时间
    NSDateFormatter *stampFormatter = [[NSDateFormatter alloc] init];
    [stampFormatter setDateFormat:@"YYYY/MM/dd"];
    //以 1970/01/01 GMT为基准，然后过了secs秒的时间
    NSDate *stampDate = [NSDate dateWithTimeIntervalSince1970:[time integerValue]/1000];
    return [stampFormatter stringFromDate:stampDate];
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
